package com.tang.service.impl;

import com.baidu.aip.imageclassify.AipImageClassify;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.tang.config.BaseContext;
import com.tang.entity.*;
import com.tang.mapper.*;
import com.tang.pojo.BooldSugarVO;
import com.tang.pojo.HistoryVO;
import com.tang.pojo.IndexVO;
import com.tang.pojo.Result;
import com.tang.service.CommonService;
import com.tang.service.DayIndexService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Slf4j
@Service
public class CommonServiceImpl implements CommonService {


    @Autowired
    TakeFoodMapper takeFoodMapper;

    @Autowired
    FoodMapper foodMapper;

    @Autowired
    XuetangMapper xuetangMapper;

    @Autowired
    DayIndexMapper dayIndexMapper;

    @Autowired
    TongzhiMapper tongzhiMapper;

    private static final String APP_ID = "97920311";
    private static final String API_KEY = "Fpa8AYJJrwrVD3dkkQuWYC74";
    private static final String SECRET_KEY = "rHsY25Xi0ADV2wlmJai88OKTbtDi1ZC1";


    @Override
    @Transactional
    public IndexVO index() {
        String value=tongzhiMapper.getById(1);
        IndexVO indexVO = new IndexVO(0);
        indexVO.setTongzhi(value);
        List<TakeFood> foodListByUserIdAndTIme =
                takeFoodMapper.getFoodListByUserIdAndTIme(BaseContext.getCurrentId(),
                        LocalDate.now().toString());

        foodListByUserIdAndTIme.forEach(takeFood -> {
            Double count = takeFood.getCount() / 100;
            Food food = foodMapper.getById(takeFood.getFoodId());
            indexVO.setIndex0((int) (indexVO.getIndex0() + food.getCalories() * count));
            indexVO.setIndex1((int) (indexVO.getIndex1() + food.getSugar() * count));
            indexVO.setIndex2((int) (indexVO.getIndex2() + food.getFat() * count));
            indexVO.setIndex3((int) (indexVO.getIndex3() + food.getProtein() * count));

        });
        LocalDateTime now = LocalDateTime.now(); // 当前的日期时间

        // 获取当天零点
        LocalDateTime startOfDay = now.with(LocalTime.MIDNIGHT);
        now = now.plusHours(1L);

        List<Xuetang> xuetangList = xuetangMapper.getByUserIdAndTime(BaseContext.getCurrentId(), startOfDay.toString(), now.toString());
        List<BooldSugarVO> result = new ArrayList<>();
        xuetangList.forEach(xuetang -> {
            result.add(new BooldSugarVO(xuetang.getTime(), xuetang.getRecord()));
        });
        indexVO.setBold(result);


        return indexVO;
    }

    @Override
    public void record(Double record) {
        Long userId = BaseContext.getCurrentId();
        xuetangMapper.record(userId, record, LocalDateTime.now().toString());
    }

    @Override
    public Result<String> updata(String photo) {
        AipImageClassify client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);
        //
//        HashMap<String, String> options = new HashMap<String, String>();
//        options.put("top_num", "3");
//        options.put("filter_threshold", "0.7");
//        options.put("baike_num", "5");
//        HashMap<String, String> options = new HashMap<String, String>();
//        options.put("baike_num", "5");
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("top_num", "3");
        options.put("filter_threshold", "0.7");
        options.put("baike_num", "5");


        byte[] file = base64ToBytes(photo);
        JSONObject jsonObject = client.dishDetect(file, options);
        String name = jsonObject.getJSONArray("result").getJSONObject(0).getString("name");

        System.out.print(jsonObject.toString(2));


        return Result.success(name);

    }

    @Override
    public Result<String> chat(String question) {
        log.info("user ai：" + question);
        // 使用安全认证AK/SK鉴权，替换下列示例中参数，安全认证Access Key替换your_iam_ak，Secret Key替换your_iam_sk
        Qianfan qianfan = new Qianfan("ALTAKOaFmaGqEUOZYeikybTl8v",
                "102416f7ab9345daa4f205e8375fef54");

        try {// 指定模型
            ChatResponse resp = qianfan.chatCompletion()
                    .model("ERNIE-Speed-8K")
                    .addMessage("user", question)
                    .execute();
            System.out.println(resp.getResult());
            return Result.success(resp.getResult());
        } catch (Exception e) {
            log.error(e.toString());
            return Result.success("系统服务故障 请稍后重试");
        }

    }

    @Override
    public Result<HistoryVO> getHistory() {
        Long userId=BaseContext.getCurrentId();
        List<Xuetang> xuetangList = xuetangMapper.getByUserId(userId);
        LocalDate date =LocalDate.now();
        DayIndex dayIndex=new DayIndex();
        List<TakeFood> takefoods =
                takeFoodMapper.getFoodListByUserIdAndTIme(BaseContext.getCurrentId(), date.toString());
        takefoods.forEach(takeFood -> {
            Food food = foodMapper.getById(takeFood.getFoodId());
            Double count = takeFood.getCount()/100;
            dayIndex.setSugar(food.getSugar()*count+ dayIndex.getSugar());
            dayIndex.setFat(food.getFat()*count+ dayIndex.getFat());
            dayIndex.setProtein(food.getProtein()*count+ dayIndex.getProtein());
            dayIndex.setCalories(food.getCalories()*count+ dayIndex.getCalories());

        });
        dayIndex.setUserId(BaseContext.getCurrentId());
        dayIndex.setTime(new Date());
        DayIndex old=dayIndexMapper.getByUserIdAndDay(BaseContext.getCurrentId(), date.toString());
        if(old ==null){
            dayIndexMapper.insert(dayIndex);
        }
        else{
            dayIndex.setId(old.getId());
            dayIndexMapper.updateById(dayIndex);
        }

        List<DayIndex> dayindexs = dayIndexMapper.getByUserId(BaseContext.getCurrentId());

        HistoryVO historyVO = new HistoryVO();
        historyVO.setDiet(dayindexs);
        historyVO.setBloodSugar(xuetangList);
        return Result.success(historyVO);

    }

    @Override
    public Result confirm(ConfirmDTO dto) {
        String name = dto.getName();
        List<Food> food = foodMapper.getByFoodName(name);
        if (food == null || food.size() == 0) {
            //  foodMapper.add(name);
            return Result.error("联系管理员，数据库没有该食物");
        }
        TakeFood takeFood = new TakeFood();
        takeFood.setFoodId(food.get(0).getId());
        takeFood.setTime(new Date());
        takeFood.setUserId(BaseContext.getCurrentId());
        takeFood.setType(dto.getType());
        takeFoodMapper.insert(takeFood);
        return Result.success();
    }


    public static byte[] base64ToBytes(String base64String) {
        Base64.Decoder decoder = Base64.getDecoder();
        return decoder.decode(base64String);
    }
}
